package com.tg.appcommon.android;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.text.TextUtils;

import com.tange.base.toolkit.StringUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.module.appcommon.R;
import com.tange.module.core.wifi.scan.WiFiScanManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Describe:
 * Created by Rance Rang on 2019/5/24.
 * <p>
 * Copyright (c) Tange.Inc All rights reserved.
 */
public class PermissionUtil {
    private static final String TAG = "PermissionUtil";
    public static final String MANAGE_EXTERNAL_STORAGE = "android.permission.MANAGE_EXTERNAL_STORAGE";


    public static final int PERMISSON_REQUESTCODE = 0;
    /**
     * 需要进行检测的权限数组
     */
    public final static String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    private Context context;

    public void checkPermissionFirst(String permission, Runnable onPermissionGrantedCallback, String title, String content) {
        checkPermissionFirst(permission, onPermissionGrantedCallback, null, true, title, content);
    }

    public void checkPermissionFirst(String permission, Runnable onPermissionGrantedCallback, Runnable onPermissionDeniedCallback, boolean invokeAfterNewGranted, String title, String content) {
        if (context == null || TextUtils.isEmpty(permission)) return;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Android 6.0 以上申请
            TGLog.i(TAG, "[checkPermissionFirst] higher than android M");

            int state = ContextCompat.checkSelfPermission(context, permission);
            if (state == PackageManager.PERMISSION_GRANTED) {
                TGLog.i(TAG, "[checkPermissionFirst] permission already granted");
                if (onPermissionGrantedCallback != null) {
                    onPermissionGrantedCallback.run();
                }
            } else {
                TGLog.i(TAG, "[checkPermissionFirst] permission NOT granted");
                if (context instanceof Activity) {
                    TGLog.i(TAG, "[checkPermissionFirst] show permission request");
                    XXPermissions.with(context).permission(permission)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    // do nothing.
                                    TGLog.i(TAG, "[checkPermissionFirst] permission granted after new request");
                                    if (invokeAfterNewGranted) {
                                        if (onPermissionGrantedCallback != null) {
                                            onPermissionGrantedCallback.run();
                                        }
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    TGLog.i(TAG, "[checkPermissionFirst] permission DENIED after new request");
                                    if (!TextUtils.isEmpty(title) || !TextUtils.isEmpty(content)){
                                        showSettingAlertDialog(title, content, context.getString(R.string.permission_settings), context.getString(R.string.cancel), onPermissionDeniedCallback);
                                    } else {
                                        if (onPermissionDeniedCallback != null && invokeAfterNewGranted) {
                                            onPermissionDeniedCallback.run();
                                        }
                                    }
                                }
                            });
                } else {
                    TGLog.i(TAG, "[checkPermissionFirst] not in a activity !");
                }
            }
        } else {
            TGLog.i(TAG, "[checkPermissionFirst] under android M");
            if (onPermissionGrantedCallback != null) {
                onPermissionGrantedCallback.run();
            }
        }
    }

    public void checkPermissionFirst(Runnable onPermissionGrantedCallback, Runnable onPermissionDeniedCallback, boolean invokeAfterNewGranted, String title, String content, String... permissions) {
        if (context == null || permissions == null) return;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Android 6.0 以上申请
            TGLog.i(TAG, "[checkPermissionFirst] higher than android M");

            boolean isGranted = true;
            for (String s : permissions) {
                int state = ContextCompat.checkSelfPermission(context, s);
                if (PackageManager.PERMISSION_GRANTED != state) {
                    isGranted = false;
                    break;
                }
            }

            if (isGranted) {
                TGLog.i(TAG, "[checkPermissionFirst] permission already granted");
                if (onPermissionGrantedCallback != null) {
                    onPermissionGrantedCallback.run();
                }
            } else {
                TGLog.i(TAG, "[checkPermissionFirst] permission NOT granted");
                if (context instanceof Activity) {
                    TGLog.i(TAG, "[checkPermissionFirst] show permission request");
                    XXPermissions.with(context).permission(permissions)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    // do nothing.
                                    TGLog.i(TAG, "[checkPermissionFirst] permission granted after new request");
                                    if (invokeAfterNewGranted) {
                                        if (onPermissionGrantedCallback != null) {
                                            onPermissionGrantedCallback.run();
                                        }
                                    }
                                }

                                @Override
                                public void onDenied(List<String> permissions, boolean never) {
                                    TGLog.i(TAG, "[checkPermissionFirst] permission DENIED after new request");
                                    if (!TextUtils.isEmpty(title) || !TextUtils.isEmpty(content)){
                                        showSettingAlertDialog(title, content, context.getString(R.string.permission_settings), context.getString(R.string.cancel), onPermissionDeniedCallback);
                                    } else {
                                        if (onPermissionDeniedCallback != null && invokeAfterNewGranted) {
                                            onPermissionDeniedCallback.run();
                                        }
                                    }
                                }
                            });
                } else {
                    TGLog.i(TAG, "[checkPermissionFirst] not in a activity !");
                }
            }
        } else {
            TGLog.i(TAG, "[checkPermissionFirst] under android M");
            if (onPermissionGrantedCallback != null) {
                onPermissionGrantedCallback.run();
            }
        }
    }

    public void showSettingAlertDialog(String title, String content, String positive, String negative, Runnable onPermissionDeniedCallback) {
        new TGAlertDialog(context)
                .builder()
                .setPosButtonColor(R.color.alert_positive_color)
                .setTitle(title)
                .setMessage(content)
                .setPositiveButton(positive, v -> {
                    openPermission();
                })
                .setNegativeButton(negative, v -> {
                    if (onPermissionDeniedCallback != null) {
                        onPermissionDeniedCallback.run();
                    }
                })
                .show();
    }


    public PermissionUtil(Context context) {
        this.context = context;
    }

    public boolean check(String permission) {
        return ContextCompat.checkSelfPermission(this.context, permission) ==
                PackageManager.PERMISSION_GRANTED;
    }

    public boolean shouldShowRequestPermissionRationale(Activity activity, String permission) {
        return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    public List<String> findDeniedPermissions(Activity activity, String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<>();
        //for (循环变量类型 循环变量名称 : 要被遍历的对象)
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(activity,
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    activity, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检查权限
     *
     * @param
     * @since 2.5.0
     */
    public boolean checkPermissions(Activity activity, int requestCode, String... permissions) {
        return checkPermissions(activity, requestCode, null, permissions);
    }

    public boolean checkPermissions(Activity activity, int requestCode, PermissionDialogListener permissionDialogListener, String... permissions) {
        //获取权限列表
        List<String> needRequestPermissonList = findDeniedPermissions(activity, permissions);
        if (null != needRequestPermissonList && needRequestPermissonList.size() > 0) {
            //list.toarray将集合转化为数组
            ActivityCompat.requestPermissions(activity,
                    needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]),
                    requestCode);

            if (permissionDialogListener != null) {
                permissionDialogListener.alertDialog(false, true);
            }
            return false;
        }
        if (permissionDialogListener != null) {
            permissionDialogListener.alertDialog(true, false);
        }
        return true;
    }

    /**
     * 检查权限
     *
     * @param
     * @since 2.5.0
     */
    public boolean checkPermissionsImpl(Activity activity, PermissionDialogListener permissionDialogListener, String[] permissions) {
        if (WiFiScanManager.scanner().isLocationEnabled(activity)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return checkPermissions(activity, PermissionUtil.PERMISSON_REQUESTCODE, permissionDialogListener, permissions);
            }
            return true;
        }
        DialogUtil.openGpsService(activity);
        return false;
    }


    public boolean checkPermissions(Activity activity, String title, String message, PermissionDialogListener permissionDialogListener, String[] permissions) {
        if (WiFiScanManager.scanner().isLocationEnabled(activity)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return checkPermissions(activity, PermissionUtil.PERMISSON_REQUESTCODE, permissionDialogListener, permissions);
            }
            return true;
        }
        DialogUtil.openGpsService(activity, title, message);
        return false;
    }

    public boolean checkPermissions(Activity activity) {
        return checkPermissionsImpl(activity, null, needPermissions);
    }

    public static boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    public void showDialog(String title, String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(R.string.permission_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                openPermission();
            }
        });
        builder.create().show();
    }

    public void showDialog(String title, String content, String positive, String negative) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
        builder.setTitle(title);
        builder.setMessage(content);
        builder.setPositiveButton(positive, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                openPermission();
            }
        });
        if (!StringUtils.isEmpty(negative)) {
            builder.setNegativeButton(negative, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
        }

        builder.create().show();
    }

    public void openPermission() {
        String sdk = android.os.Build.VERSION.SDK; // SDK号

        String model = android.os.Build.MODEL; // 手机型号

        String release = android.os.Build.VERSION.RELEASE; // android系统版本号
        String brand = Build.BRAND;//手机厂商
        if (TextUtils.equals(brand.toLowerCase(), "redmi") || TextUtils.equals(brand.toLowerCase(), "xiaomi")) {
            gotoMiuiPermission();//小米
        } else if (TextUtils.equals(brand.toLowerCase(), "meizu")) {
            gotoMeizuPermission();
        } else if (TextUtils.equals(brand.toLowerCase(), "huawei") || TextUtils.equals(brand.toLowerCase(), "honor")) {
            gotoHuaweiPermission();
        } else {
            context.startActivity(getAppDetailSettingIntent());
        }
    }


    /**
     * 跳转到miui的权限管理页面
     */
    private void gotoMiuiPermission() {
        try { // MIUI 8
            Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", context.getPackageName());
            context.startActivity(localIntent);
        } catch (Exception e) {
            try { // MIUI 5/6/7
                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                localIntent.putExtra("extra_pkgname", context.getPackageName());
                context.startActivity(localIntent);
            } catch (Exception e1) { // 否则跳转到应用详情
                context.startActivity(getAppDetailSettingIntent());
            }
        }
    }

    /**
     * 跳转到魅族的权限管理系统
     */
    private void gotoMeizuPermission() {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            TGLog.d(TGLog.TAG, "packageName = " + context.getPackageName());
            intent.putExtra("packageName", context.getPackageName());
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent());
        }
    }

    /**
     * 华为的权限管理页面
     */
    private void gotoHuaweiPermission() {
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
            intent.setComponent(comp);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent());
        }

    }

    /**
     * 获取应用详情页面intent（如果找不到要跳转的界面，也可以先把用户引导到系统设置页面）
     *
     * @return
     */
    private Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        return localIntent;
    }

    public interface PermissionDialogListener {
        void alertDialog(boolean permission, boolean showDialog);
    }


}
